//
//  LoginViewController.m
//  RentCar
//
//  Created by sunmingming on 14-4-1.
//  Copyright (c) 2014年 Ebola. All rights reserved.
//

#import "Register1ViewController.h"
#import "AboutSWViewController.h"

@interface Register1ViewController ()<UIAlertViewDelegate>

@property(nonatomic,weak) IBOutlet UIImageView *zyImage;
@property(nonatomic,weak) IBOutlet UILabel *zyLabel;

@property(nonatomic,weak) IBOutlet UITextField *nameField;
@property(nonatomic,weak) IBOutlet UITextField *passField;
@property(nonatomic,weak) IBOutlet UITextField *messField;

@property(nonatomic,weak) IBOutlet UIButton *loginButton;
@property(nonatomic,weak) IBOutlet UIButton *registerButton;
@property(nonatomic,weak) IBOutlet UIButton *forgetPassButton;
@property(nonatomic,weak) IBOutlet UIButton *messageButton;
@property(nonatomic,assign) int codeTime;
@property(nonatomic,strong) NSTimer *codeTimer;
@property(nonatomic,strong) NSString *aCodeStr;
@property(nonatomic,strong) NSString *aTeleStr;

typedef enum
{
    ESoapGetCode = 0,
    ESoapRegister,
}EHTTPWays;
@property(nonatomic,assign) EHTTPWays myHTTPWay;

-(IBAction)loginPressed:(id)sender;
-(IBAction)forgetPassPressed:(id)sender;
-(IBAction)registerPressed:(id)sender;
-(IBAction)messagePressed:(id)sender;

@end

@implementation Register1ViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"注册领头洋";
        self.navigationItem.leftBarButtonItem =
        [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"arrow_white"]
                                         style:UIBarButtonItemStyleDone
                                        target:self
                                        action:@selector(backPressed:)];
        self.aCodeStr = @"";
        self.aTeleStr = @"";
        self.codeTimer = nil;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self showError:nil];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.loginButton.enabled = YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)showError:(NSString*)aStr
{
    if((!aStr) || aStr.length <= 0)
    {
        self.zyImage.hidden = YES;
        self.zyLabel.hidden = YES;
    }
    else
    {
        self.zyImage.hidden = NO;
        self.zyLabel.hidden = NO;
        self.zyLabel.text = aStr;
    }
}

-(IBAction)loginPressed:(id)sender
{
    NSString *nameStr = [self.nameField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *passStr = [self.passField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *messStr = [self.messField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if(nameStr.length <= 0)
    {
        [self showError:@"请填写用户名"];
        return;
    }
    if(passStr.length <= 0)
    {
        [self showError:@"请填写密码"];
        return;
    }
    if(messStr.length <= 0)
    {
        [self showError:@"请两次填写您的密码"];
        return;
    }
    /*
    if(![tooles validateTelephone:nameStr])
    {
        [self showError:@"请正确填写手机号码！"];
        return;
    }
    if(![tooles validatePassword:passStr])
    {
        [self showError:@"密码请输入6位以上！"];
        return;
    }
    if((![self.messField.text isEqualToString:self.aCodeStr])
       && ([nameStr isEqualToString:self.aTeleStr]))
    {
        [self showError:@"请输入正确的激活码！"];
        return;
     }
     */
    [self resignAllTextField];
    if(!self.forgetPassButton.selected)
    {
        [self showError:@"请先阅读并同意我们的协议"];
        return;
    }
    [self showError:nil];
    [self.codeTimer invalidate];
    self.codeTimer = nil;
    self.messageButton.enabled = YES;
    self.messageButton.backgroundColor = [UIColor redColor];
    [self AskSoapForHTTPWay:ESoapRegister];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self resignAllTextField];
}

-(void)resignAllTextField
{
    [self.nameField resignFirstResponder];
    [self.passField resignFirstResponder];
    [self.messField resignFirstResponder];
}

-(IBAction)registerPressed:(id)sender
{
    [self resignAllTextField];
    AboutSWViewController *vc = [AboutSWViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}

-(IBAction)forgetPassPressed:(id)sender
{
    [self resignAllTextField];
    self.forgetPassButton.selected = !self.forgetPassButton.selected;
}

-(IBAction)messagePressed:(id)sender
{
    [self resignAllTextField];
    if(![[self.messageButton titleForState:UIControlStateNormal]
        hasPrefix:@"发送"])
        return;
    NSString *nameStr = [self.nameField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if(nameStr.length <= 0)
    {
        [self showError:@"请填写手机号码！"];
        return;
    }
    /*
    if(![tooles validateTelephone:nameStr])
    {
        [self showError:@"请正确填写手机号码！"];
        return;
    }
     */
    [self showError:nil];
    self.messageButton.enabled = NO;
    self.messageButton.backgroundColor = [UIColor grayColor];
    [self startToCountDown];
    [self AskSoapForHTTPWay:ESoapGetCode];
}

-(void)startToCountDown
{
    self.codeTime = 10;
    self.codeTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(countDown:) userInfo:nil repeats:YES];
    [self.messageButton setTitle:[NSString stringWithFormat:@"(%d秒)",self.codeTime] forState:UIControlStateNormal];
}

-(void)countDown:(id)sender
{
    NSLog(@"down...");
    self.codeTime--;
    if(self.codeTime >= 0)
    {
        [self.messageButton setTitle:[NSString stringWithFormat:@"(%d秒)",self.codeTime] forState:UIControlStateNormal];
    }
    else
    {
        [self.codeTimer invalidate];
        self.codeTimer = nil;
        self.messageButton.enabled = YES;
        self.messageButton.backgroundColor = [UIColor redColor];
        [self.messageButton setTitle:@"发送激活码" forState:UIControlStateNormal];
    }
}

-(void)backPressed:(id)sender
{
    [self.codeTimer invalidate];
    self.codeTimer = nil;
    [self resignAllTextField];
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)dealloc
{
    [self.codeTimer invalidate];
    self.codeTimer = nil;
    self.nameField = nil;
    self.passField = nil;
    self.messField = nil;
    self.loginButton = nil;
    self.registerButton = nil;
    self.forgetPassButton = nil;
    self.messageButton = nil;
    self.aTeleStr = nil;
    self.aCodeStr = nil;
}

-(void)AskSoapForHTTPWay:(EHTTPWays)aHTTPWay
{
    self.myHTTPWay = aHTTPWay;
    switch (self.myHTTPWay) {
        case ESoapGetCode:
        {
            /*
            [AVCloud callFunctionInBackground:@"auth_vcode" withParameters:parameters block:^(id object, NSError *error) {
                // 执行结果
                if (!error && object) {
                    NSLog(@"avget:%@",object);
                    NSDictionary *aSucData = [NSJSONSerialization JSONObjectWithData: [object dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableLeaves error: &error];
                    switch ([[aSucData valueForKey:@"success"] intValue]) {
                        case 0:
                        {
                            [tooles showGlobalAlertWithTitle:@"" andMsg:[aSucData valueForKey:@"msg"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                            [self.loginButton setEnabled:YES];
                        }
                            break;
                        case 1:
                        {
                            self.aCodeStr = [aSucData valueForKey:@"vcode"];
                            self.aTeleStr = self.nameField.text;
                            [tooles
                             showGlobalAlertWithTitle:@"请查收激活码"
                             andMsg:@"激活码已发送到您的手机号码，请注意查收！"
                             delegate:nil
                             cancelButtonTitle:@"确认"
                             otherButtonTitles:nil];
                        }
                            break;
                        default:
                            break;
                            
                    }
                    [SVProgressHUD dismiss];
                } else {
                    [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@", error]];
                }
            }];
             */
        }
            break;
        case ESoapRegister:
        {
            [SVProgressHUD showWithStatus:@"loading..."];
            NSDictionary *PA = @{@"username": self.nameField.text,
                                 @"password":self.passField.text,
                                 @"password2":self.messField.text};
            [APPALL.netSession POST:[NSString stringWithFormat:@"%@%@",APIURL,APIReg]
                         parameters:PA
                           progress:nil
                            success:^(NSURLSessionDataTask * task, id responseObject){
                                NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                                NSLog(@"JSON: %@", JSON[@"register"]);
                                if([JSON[@"register"] isEqualToString:@"success"]){
                                    [SVProgressHUD showSuccessWithStatus:@"注册成功"];
                                    APPALL.myUserItem.username = self.nameField.text;
                                    APPALL.myUserItem.password = self.passField.text;
                                    [self.navigationController popViewControllerAnimated:YES];
                                }else{
                                    [SVProgressHUD showErrorWithStatus:@"注册失败"];
                                }
                                
                            }
                            failure:^(NSURLSessionDataTask * task, NSError * error){
                                [SVProgressHUD dismiss];
                                //[SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"请求失败:%@", error.description]];
                            }];
        }
            break;
        default:
            break;
    }
}

@end
